#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "Log.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"

#define PORT 7777

class HttpServer
{
    private:
        int _port;
        bool _stop;
    public:
        HttpServer(int port = PORT)
            : _port(port)
            , _stop(false)
        {}
        void InitServer()
        {
            // 信号SIGPIPE进行忽略，否则在写入时候，可能直接崩溃server
            signal(SIGPIPE, SIG_IGN); 
        }
        void Loop()
        {
            TcpServer *tsvr = TcpServer::GetInstance(_port);
            LOG(INFO, "Loop begin");
            while(!_stop)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len);
                if(sock < 0) // 获取套接字失败
                {
                    continue;
                }
                LOG(INFO, "Get a new link");
                int *_sock = new int(sock); // 暂时方案
                pthread_t pid;
                pthread_create(&pid, nullptr, Entrance::HandlerRequest, _sock);
                pthread_detach(pid);
            }
        }
        ~HttpServer()
        {}
};
